<?php

namespace App\Model;

use Hyperf\DbConnection\Db;

class MjSignLog extends Model
{

    // 表名
    protected $table = 'mj_sign_log';

    public $timestamps = true;

    protected $dateFormat = 'Y-m-d H:i:s';

    const CREATED_AT = 'createtime';

    const UPDATED_AT = 'updatetime';

    public function setSignDataAttribute($value)
    {
        $this->attributes['sign_data'] = $value ? json_encode($value) : '';
    }

    public function getSignDataAttribute($value)
    {
        return $value ? json_decode($value, true) : [];
    }

    public function setSignPeriodDataAttribute($value)
    {
        $this->attributes['sign_period_data'] = $value ? json_encode($value) : '';
    }

    public function getSignPeriodDataAttribute($value)
    {
        return $value ? json_decode($value, true) : [];
    }

    //  查询签到记录
    public static function getSignLogByUid($uid)
    {
        return self::query()->where('user_id', $uid)->first();
    }

    //  添加签到记录
    public static function addSignLog(int $uid, int $week, string $dateTime, $historyData = [])
    {
        $log = self::getSignLogByUid($uid);
        if (!$log) {
            $log = new MjSignLog;
            $signData = [];
            $signPeriodData = [];
            $num = 0;
            if ($historyData) {
                $signPeriodData = $historyData['sign_period_data'];
                $signData = $historyData['sign_data'];
                $num = count($signData);
            }
            $signData[$dateTime] = $week;
            $log->user_id = $uid;
            $log->sign_data = $signData;
            $log->sign_period_data = $signPeriodData;
            $log->num = $num + 1;
        } else {
            $signData = $log->sign_data;
            $signData[$dateTime] = $week;
            $log->sign_data = $signData;
            $log->num += 1;
        }
        return $log->save();
    }

    //  添加签到记录
    public static function addSignPeriodLog(int $uid, int $type)
    {
        $log = self::getSignLogByUid($uid);
        if (!$log) {
            $log = new MjSignLog;
            $sign_period_data = [];
        } else {
            $sign_period_data = $log->sign_period_data;
        }
        $sign_period_data[] = $type;
        $log->user_id = $uid;
        $log->sign_period_data = array_unique($sign_period_data);
        return $log->save();
    }

}
